import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Input, Button, Select } from 'antd';
import queryString from 'query-string';
import moment from 'moment';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';

const FormItem = Form.Item;
const { Option } = Select;

@connect(({ annualbasic, loading }) => ({
  annualbasic,
  tabList: annualbasic.tabList,
  loading: loading.models.annualbasic,
  pageImportData: annualbasic.pageImportData,
  formFieldsValue: annualbasic.formFieldsValue,
  expandForm: annualbasic.expandForm,
  paymentOpts: annualbasic.paymentOpts,
  ADJ_FINIASH_TYPE: annualbasic.ADJ_FINIASH_TYPE,
  PAY_FEES_WAY: annualbasic.PAY_FEES_WAY,
}))
@Form.create()
class AdjustBase extends PureComponent {
  state = {
    selectedRowKeys: [],
    selectedRows: [],
  };

  tableSearchLayout = {
    labelCol: { md: { span: 7 } },
    wrapperCol: { md: { span: 17 } },
  };

  componentDidMount() {
    const { location } = this.props;
    const { yearAdjTskId } = queryString.parse(location.search);
    this.setState(
      {
        yearAdjTskId,
      },
      () => {
        this.getList();
      }
    );
    this.getDictionaries();
  }

  // 字典
  getDictionaries = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'annualbasic/fetchDictionaries',
      payload: ['ADJ_FINIASH_TYPE', 'PAY_FEES_WAY'],
    });
  };

  handleSelectRows = (rows, rowKeys) => {
    this.setState({ selectedRows: rows, selectedRowKeys: rowKeys });
  };

  // 申报结果导入
  ImportDeclarationResults = record => {
    router.push({
      pathname: '/more/annualbasicadjust/importdeclprogress',
      query: {
        yearAdjTskId: record.yearAdjTskId,
        accoId: record.accoId,
      },
    });
  };

  // 获取列表
  getList = (currentPage = 1, pageSize = 10) => {
    const { form, dispatch } = this.props;
    const { yearAdjTskId } = this.state;
    form.validateFields(['accoName', 'payWay', 'state'], (err, fieldsValue) => {
      if (err) return;
      const pageArg = { currentPage, pageSize };
      const params = {
        yearAdjTskId,
        ...fieldsValue,
        pageArg,
      };
      dispatch({
        type: 'annualbasic/fetchImportDeclList',
        payload: params,
      });
    });
  };

  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'annualbasic/updateModelData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 渲染简单表单
  renderSimple() {
    const {
      form: { getFieldDecorator },
      PAY_FEES_WAY,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="缴纳方式" {...this.tableSearchLayout}>
              {getFieldDecorator('payWay', {
                initialValue: '0',
              })(
                <Select
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  placeholder="请选择"
                  style={{ width: '100%' }}
                >
                  {PAY_FEES_WAY.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="账户名称" {...this.tableSearchLayout}>
              {getFieldDecorator('accoName', {})(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ marginBottom: 24 }}>
              <Button type="primary" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开
                <DownOutlined />
              </a>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  // 渲染完整表单
  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      PAY_FEES_WAY,
      ADJ_FINIASH_TYPE,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="缴纳方式" {...this.tableSearchLayout}>
              {getFieldDecorator('payWay', {
                initialValue: '0',
              })(
                <Select
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  placeholder="请选择"
                  style={{ width: '100%' }}
                >
                  {PAY_FEES_WAY.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="账户名称" {...this.tableSearchLayout}>
              {getFieldDecorator('accoName', {})(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态" {...this.tableSearchLayout}>
              {getFieldDecorator('state', {
                initialValue: '0',
              })(
                <Select
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  placeholder="请选择"
                  style={{ width: '100%' }}
                >
                  {ADJ_FINIASH_TYPE.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24} offset={16}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                收起
                <UpOutlined />
              </a>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm = () => {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimple();
  };

  render() {
    const { loading, pageImportData } = this.props;
    const { selectedRowKeys, selectedRows } = this.state;

    const columns1 = [
      {
        title: '序号',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: (text, record, index) => `${index + 1}`,
      },
      {
        title: '缴纳方式',
        dataIndex: 'payWayName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '账户名称',
        dataIndex: 'accoName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '生效年月',
        dataIndex: 'validYm',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: text => moment(text).format('YYYY-MM'),
      },

      {
        title: '状态',
        dataIndex: 'stateName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },

      {
        title: '涉及人员',
        dataIndex: 'planColtNum',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '导入人员',
        dataIndex: 'realColtNum',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '操作',
        width: 200,
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.ImportDeclarationResults(record)}>申报结果导入</a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Card style={{ marginBottom: 16 }} bordered={false}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card bordered={false}>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={pageImportData}
            rowKey="accoId"
            columns={columns1}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <FooterToolbar style={{ width: '100%' }}>
          <Button onClick={() => router.goBack()}>返回</Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

export default AdjustBase;
